import 'package:flutter/services.dart';
import 'package:flutter_wisave/Common/CustomTheme.dart';
import 'package:flutter_wisave/HomePage/ModuleItem.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';
import 'package:flutter/material.dart';
import 'HomePage/NewsItem.dart';
import 'package:flutter_wisave/Tools/NetworkService.dart';
import 'package:flutter_wisave/HomePage/Class/NoticeClass.dart';
import 'package:flutter_wisave/CentrePage/Production/ProductionPage.dart';
import 'package:flutter_wisave/CentrePage/Device/EquipmentPage.dart';
import 'package:flutter_wisave/CentrePage/Quality/QualityPage.dart';
import 'package:flutter_wisave/CentrePage/Energy/EnergyPage.dart';
import '../../Tools/ToolsLocalStorage.dart';
import 'package:flutter_wisave/LoginPage/LoginPage.dart';
import 'package:flutter_wisave/HomePage/ScanPage.dart';
import 'package:flutter_wisave/main.dart' as mainApp;
import 'widgets/AppColors.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final NetworkService _networkService = NetworkService();
  List<dynamic> notices = [];
  List<String> deptList = [];
  List<dynamic> deptdyList = [];
  var childDeptName = '';
  // String selected_DeptName = '';

  @override
  void initState() {
    // super.initState();
    _networkService.setupInterceptors(context);
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _checkToken();
      _loadData();
      _loadDeptData();
    });
  }

  Future<void> _checkToken() async {
    final token = await LocalStorage.getstr('token');
    if (token == null || token.isEmpty || token == 'null') {
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => const LoginPage()),
      );
    }
  }

  // @override
  // void didChangeDependencies() {
  //   super.didChangeDependencies();
  //   if (notices.length == 0) {
  //     _loadData();
  //   }
  // }

  Future<void> _loadData() async {
    childDeptName = (await LocalStorage.getstr('childDeptName'))!;
    try {
      final result = await _fetchData();
      if (result != null && result['data'] != null) {
        setState(() {
          notices = (result['data']['objectList'] as List)
              .map((item) => (item as Map<String, dynamic>))
              .toList();
        });
      } else {
        print('No data received from _fetchData');
      }
    } catch (e) {
      print('Error in _loadData: $e');
    }
  }

  Future<Map<String, dynamic>?> _fetchData() async {
    try {
      final response = await _networkService.post(
        '/miniApp/officialAccount/getContentList',
        data: {
          'pageIndex': 1,
          'pageSize': 3,
        },
      ); //  system/notice/list
      if (response.statusCode == 200) {
        return response.data;
      } else {
        print('Failed to load data: ${response.statusCode}');
        return null;
      }
    } catch (e) {
      print('Error in _fetchData: $e');
      return null;
    }
  }

  Future<void> _loadDeptData() async {
    try {
      final result = await _fetchDeptData();
      if (result != null && result['data'] != null) {
        setState(() {
          deptdyList = (result['data'] as List)
              .map((item) => (item as Map<String, dynamic>))
              .toList();
          for (var item in deptdyList) deptList.add(item['deptName']);
        });
      } else {
        print('No data received from _fetchData');
      }
    } catch (e) {
      print('Error in _loadData: $e');
    }
  }

  Future<Map<String, dynamic>> _fetchDeptData() async {
    final deptID = await LocalStorage.getstr('deptId');
    try {
      final response = await _networkService.get('/system/dept/info/$deptID');
      if (response.statusCode == 200) {
        return response.data;
      } else {
        throw Exception('steeloutday Failed to load data');
      }
    } catch (e) {
      print('steeloutday Error in _fetchData: $e');
      rethrow;
    }
  }

  Future<void> _changeDeptData(String deptName) async {
    var ID = '';
    for (var item in deptdyList) {
      if (item['deptName'] == deptName) {
        ID = item['deptId'].toString();
      }
    }
    try {
      final result = await _fetchChangeData(ID);
      if (result != null) {
        LocalStorage.setstr('deptId', ID);
        setState(() {
          childDeptName = deptName;
        });
      } else {
        print('No data received from _fetchData');
      }
    } catch (e) {
      print('Error in _loadData: $e');
    }
  }

  Future<Map<String, dynamic>> _fetchChangeData(String ID) async {
    try {
      final response =
          await _networkService.get('/system/dept/chooseChildDept?deptId=$ID');
      if (response.statusCode == 200) {
        return response.data;
      } else {
        throw Exception('steeloutday Failed to load data');
      }
    } catch (e) {
      print('steeloutday Error in _fetchData: $e');
      rethrow;
    }
  }

  @override
  Widget build(BuildContext context) {
    // 定义本地数组
    final List<Map<String, dynamic>> moduleData = [
      {
        'icon': 'assets/images/home/home_1.png',
        'title': '生产管理',
        'index': 0,
        'content': 'Device'
      },
      {
        'icon': 'assets/images/home/home_2.png',
        'title': '设备管理',
        'index': 1,
        'content': 'Produce'
      },
      {
        'icon': 'assets/images/home/home_3.png',
        'title': '质量管理',
        'index': 2,
        'content': 'Quality'
      },
      {
        'icon': 'assets/images/home/home_4.png',
        'title': '能环管理',
        'index': 3,
        'content': 'Energy ring'
      },
      {
        'icon': 'assets/images/home/home_5.png',
        'title': '云眼',
        'index': 4,
        'content': 'Monitor'
      },
      {
        'icon': 'assets/images/home/home_6.png',
        'title': '智能计算',
        'index': 5,
        'content': 'Count'
      },
    ];

    final imageData = [
      'assets/images/home/1.png',
      'assets/images/home/2.png',
      'assets/images/home/3.png',
      'assets/images/home/4.png'
    ];

    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent, // 状态栏颜色
    ));

    return Scaffold(
      backgroundColor: AppColors.backgroundColor,
      appBar: AppBar(
        centerTitle: true,
        backgroundColor: Colors.transparent, // 使 AppBar 透明
        flexibleSpace: Container(
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/images/home/home_topbg.png'),
              fit: BoxFit.fill,
            ),
          ),
        ),

        actions: [
          const SizedBox(width: 10),
          GestureDetector(
            onTap: () {},
            child: Image(
              image: AssetImage(AppColors.isDarkMode
                  ? 'assets/images/home/nav_logo_d.png'
                  : 'assets/images/home/nav_logo.png'),
              width: 76,
              height: 76,
            ),
          ),
          const SizedBox(width: 10), // 添加间隔
          Flexible(
            child: Center(
              child: TDText(
                childDeptName,
                maxLines: 1, // 限制为单行显示
                overflow: TextOverflow.ellipsis, // 超出部分显示省略号
                style: TextStyle(
                  color:
                      AppColors.textPrimary, //TDTheme.of(context).grayColor12,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
          ),
          const SizedBox(width: 10), // 添加间隔
          // GestureDetector(
          //   onTap: () {},
          //   child: const Image(
          //     image: AssetImage('assets/images/home/home_more.png'),
          //     width: 24,
          //     height: 24,
          //   ),
          // ),
          // const SizedBox(width: 10), // 添加间隔
          GestureDetector(
            onTap: () {
              // 添点击事件处理逻辑
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => const ScanPage()),
              );
            },
            child: const Image(
              image: AssetImage('assets/images/home/home_scan.png'),
              width: 24,
              height: 24,
            ),
          ),
          const SizedBox(width: 10), // 添加间隔
        ],
      ),
      body: Stack(
        children: [
          ListView(
            children: [
              Container(
                padding: EdgeInsets.all(20),
                height: 180, // 轮播图的高度
                child: Swiper(
                  autoplay: true,
                  itemCount: imageData.length,
                  loop: true,
                  pagination: const SwiperPagination(
                      alignment: Alignment.bottomCenter,
                      builder: TDSwiperPagination.dots),
                  itemBuilder: (BuildContext context, int index) {
                    return ClipRRect(
                      borderRadius: BorderRadius.circular(8),
                      child: TDImage(
                        assetUrl: imageData[index],
                        type: TDImageType.fitWidth,
                      ),
                    );
                  },
                ),
              ),
              Container(
                width: double.infinity,
                padding: EdgeInsets.only(left: 20, right: 20),
                child: Row(
                  children: [
                    const Image(
                      image: AssetImage('assets/images/home/home_notify.png'),
                      width: 24,
                      height: 24,
                    ),
                    TDText(notices.isNotEmpty ? notices[0]['title'] : '暂无通知',
                        textAlign: TextAlign.left,
                        style: TextStyle(
                          color: AppColors.textPrimary,
                          fontWeight: FontWeight.w500,
                        ),
                        font: TDTheme.of(context).fontBodyMedium),
                    const Expanded(child: SizedBox()),
                    // TDText('更多 >',
                    //     textAlign: TextAlign.right,
                    //     textColor: TDTheme.of(context).fontGyColor3,
                    //     font: TDTheme.of(context).fontBodyExtraSmall),
                  ],
                ),
              ),
              Container(
                width: double.infinity,
                height: 273,
                padding: const EdgeInsets.all(10),
                margin: const EdgeInsets.all(10),
                // decoration: BoxDecoration(
                //   borderRadius: BorderRadius.circular(10),
                //   border: Border.all(color: AppColors.dividerColor),
                //   color: AppColors.cardColor, // Colors.white,
                //   boxShadow: TDTheme.of(context).shadowsMiddle,
                // ),
                child: GridView.builder(
                  physics: const NeverScrollableScrollPhysics(), // 禁止滑动
                  gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 3, // 每行显示三个项
                    childAspectRatio: 1, // 控制子项的宽高比
                    mainAxisSpacing: 10, // 设置行间距
                    crossAxisSpacing: 10, // 设置列间距
                  ),
                  itemCount: moduleData.length,
                  itemBuilder: (context, index) {
                    final item = moduleData[index];
                    return GestureDetector(
                      onTap: () {
                        if (index == 0) {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => const ProductionPage()),
                          ).then((result) {
                            if (result != null) {
                              ScaffoldMessenger.of(context).showSnackBar(
                                SnackBar(
                                    content: Text('Received: $result',
                                        style: TextStyle(
                                            color: AppColors.textSecondary))),
                              );
                            }
                          });
                        } else if (index == 1) {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => const EquipmentPage()),
                          ).then((result) {
                            if (result != null) {
                              ScaffoldMessenger.of(context).showSnackBar(
                                SnackBar(
                                    content: Text('Received: $result',
                                        style: TextStyle(
                                            color: AppColors.textSecondary))),
                              );
                            }
                          });
                        } else if (index == 2) {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => const QualityPage()),
                          ).then((result) {
                            if (result != null) {
                              ScaffoldMessenger.of(context).showSnackBar(
                                SnackBar(
                                    content: Text('Received: $result',
                                        style: TextStyle(
                                            color: AppColors.textSecondary))),
                              );
                            }
                          });
                        } else if (index == 3) {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => const EnergyPage()),
                          ).then((result) {
                            if (result != null) {
                              ScaffoldMessenger.of(context).showSnackBar(
                                SnackBar(
                                    content: Text('Received: $result',
                                        style: TextStyle(
                                            color: AppColors.textSecondary))),
                              );
                            }
                          });
                        } else if (index == 4) {
                          mainApp.MyApp.updateSelectedIndex(1);
                        }
                      },
                      child: ModuleItem(
                        title: item['title'],
                        icon: item['icon'],
                        index: item['index'],
                        content: item['content'],
                        w: (MediaQuery.of(context).size.width / 3) - 30,
                      ),
                    );
                  },
                ),
              ),
              Container(
                margin: EdgeInsets.only(left: 20, right: 20),
                child: Row(
                  children: [
                    TDText(
                      '资讯',
                      textAlign: TextAlign.left,
                      font: TDTheme.of(context).fontTitleMedium,
                      style: TextStyle(
                        color: AppColors.textPrimary,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    const Expanded(child: SizedBox()),
                    GestureDetector(
                      onTap: () {
                        mainApp.MyApp.updateSelectedIndex(3);
                      },
                      child: TDText(
                        '更多 >',
                        textAlign: TextAlign.right,
                        textColor: AppColors.textPrimary,
                        font: TDTheme.of(context).fontBodyExtraSmall,
                      ),
                    ),
                  ],
                ),
              ),
              Container(
                width: double.infinity,
                margin: const EdgeInsets.only(left: 20, right: 20, top: 10),
                child: Column(
                  children: List.generate(notices.length, (index) {
                    return Container(
                      child: NewsItem(data: notices[index]),
                    );
                  }),
                ),
              )
            ],
          ),
        ],
      ),
    );
  }
}
